<template>
  <div>
    <el-cascader ref="cascader" size="medium" v-model="selVal" :props="props" @change="change"></el-cascader>
  </div>
</template>
<script>
import { requireJS } from "@/assets/common";
let id = 0;

export default {
  data() {
    const self = this;
    return {
      selVal: "",
      props: {
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level } = node;
          var name = "中国";
          if (!node.root) {
            name = node.data.label;
          }
          var ls = await self.searchAll(name);
          resolve(
            ls.map(item => {
              return {
                value: item.name,
                label: item.name,
                leaf: level >= 3
              };
            })
          );
        }
      }
    };
  },
  watch: {
    value(val) {
      this.selVal = val.concat([]);
    }
  },
  props: {
    value: String
  },
  methods: {
    change() {
      this.$emit("input", this.selVal);
    },
    async getMap() {
      if (this.AMap) {
        return this.AMap;
      } else {
        this.AMap = await requireJS(
          "https://webapi.amap.com/maps?v=1.4.8&key=a42f8fc982b7fcf299e5c4579ab2c419"
        );
        return this.AMap;
      }
    },
    initSearch() {
      return new Promise(async (resolve, reject) => {
        var map = await this.getMap();
        if (this.districtSearch) {
          resolve(this.districtSearch);
        } else {
          map.plugin("AMap.DistrictSearch", () => {
            this.districtSearch = new map.DistrictSearch({
              level: "province",
              subdistrict: 1
            });
            resolve(this.districtSearch);
          });
        }
      });
    },
    async searchAll(name) {
      this.search = await this.initSearch();
      return new Promise((resolve, reject) => {
        this.search.search(name, (status, result) => {
          var list = result.districtList[0]["districtList"];
          resolve(list);
        });
      });
    }
  },
  async created() {}
};
</script>
<style lang="less">
  .el-cascader--medium {
    width: 500px;
  }
</style>